package com.example.util;

import com.example.dao.AdminDAO;
import com.example.model.UserInfo;

import javax.swing.table.AbstractTableModel;
import java.util.List;

public class UserTableModel extends AbstractTableModel {
    AdminDAO adminDAO = new AdminDAO();
    private List<UserInfo> users = adminDAO.getUserInfo();
    private final String[] columnNames = {"客户ID", "姓名", "身份证号", "电话", "地址"};



    public UserTableModel(List<UserInfo> users) {
        this.users = users;
    }

    @Override
    public int getRowCount() {
        return users.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        UserInfo user = users.get(rowIndex);
        return switch (columnIndex) {
            case 0 -> user.getCustomerId();
            case 1 -> user.getCustomerName();
            case 2 -> user.getPid();
            case 3 -> user.getTelephone();
            case 4 -> user.getAddress();
            default -> null;
        };
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        // 只有ID列不可编辑
        return columnIndex != 0;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        UserInfo user = users.get(rowIndex);
        switch (columnIndex) {
            case 1 -> user.setCustomerName((String) aValue);
            case 2 -> user.setPid((String) aValue);
            case 3 -> user.setAddress((String) aValue);
            case 4 -> user.setTelephone((String) aValue);
        }
        adminDAO.updateCustomerInfo(user);
        fireTableCellUpdated(rowIndex, columnIndex);
    }
}